import java.util.concurrent.locks.ReentrantLock;

public class TryLockExample {
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            if (lock.tryLock()) {
                try {
                    System.out.println("Thread 1 acquired the lock");
                    Thread.sleep(1000); // 模拟线程执行一段时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                    System.out.println("Thread 1 released the lock");
                }
            } else {
                System.out.println("Thread 1 failed to acquire the lock");
            }
        });

        Thread t2 = new Thread(() -> {
            if (lock.tryLock()) {
                try {
                    System.out.println("Thread 2 acquired the lock");
                    //无论是否发生异常，都会执行的代码块，通常用于资源释放或清理操作。
                } finally {
                    lock.unlock();
                    System.out.println("Thread 2 released the lock");
                }
            } else {
                System.out.println("Thread 2 failed to acquire the lock");
            }
        });

        t1.start();
        t2.start();
    }
}
